package com.jams.goodox.activity.serve.headhunter;


import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.hangzhou.jin.customview.LoadView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.ChooseItem;
import com.jams.goodox.entity.JobBean;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.resp.JobListResp;
import com.jams.goodox.listen.DialogActionListener;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.HeadHunterService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.widget.PromptBuilderDialog;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.widget.RecyclerDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * create by jams on 2017/06/06
 * <p>
 * 企业的职位搜索
 */
public class CompanyJobListSearchActivity extends BaseActivity {


    @Bind(R.id.et_job_search)
    EditText etJobSearch;
    @Bind(R.id.rcv_job_search)
    RefreshRecyclerView rcvJobSearch;
    @Bind(R.id.empty_view)
    LoadView emptyView;
    private List<JobBean> dataList;
    private int curPage;
    private List<ChooseItem> priseList;
    private String key;
    private boolean isEdited;//记录当前页面是否操作过

    @Override
    protected int getLayoutId() {
        return R.layout.activity_company_job_list_search;
    }

    @Override
    protected void init() {
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.search_gray));//沉侵式头部
        setTitleVisibility(false);
        dataList = new ArrayList<>();
        priseList = CollectionUtils.arrayToList(getResources().getStringArray(R.array.prise_need), -1);
        rcvJobSearch.setLayoutManager(new RefreshLinearLayoutManager(this));
        rcvJobSearch.setAdapter(new RecycleCommonAdapter<JobBean>(this, dataList, R.layout.company_job_list_item) {
            @Override
            public void convert(RecycleCommonViewHolder helper, final JobBean item, final int position) {
                helper.setText(R.id.company_job_name, item.getJobName())
                        .setText(R.id.company_job_money, priseList.get(item.getSalary()).getName())
                        .setText(R.id.company_job_mark, item.getRemark())
                        .setText(R.id.company_job_status, item.getStatus() == 0 ? "未发布" : "正在招聘");
                helper.getView(R.id.tv_company_job_action).setBackgroundResource(item.getStatus() == 0 ? R.drawable.main_theme_radius : R.drawable.bottom_btn_2dp_666666);
                ((TextView) helper.getView(R.id.tv_company_job_action)).
                        setTextColor(item.getStatus() == 0 ? ContextCompat.getColor(mContext, R.color.font_main) : ContextCompat.getColor(mContext, R.color.font_white));
                ((TextView) helper.getView(R.id.tv_company_job_action)).setText(item.getStatus() == 0 ? "上架职位" : "下架职位");
                helper.getView(R.id.tv_company_job_edit).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getContext(), AddJobInfoActivity.class);
                        intent.putExtra(AddJobInfoActivity.PositionId, item.getId());
                        startActivityForResult(intent, 1991);
                    }
                });
                helper.getView(R.id.tv_company_job_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        deleteJob(item.getId(), position);
                    }
                });
                helper.getView(R.id.tv_company_job_action).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showJobToUser(item, item.getStatus() == 0 ? 1 : 0);
                    }
                });
            }
        });
        etJobSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    curPage = 1;
                    key = etJobSearch.getText().toString();
                    search();
                }
                return false;
            }
        });
        rcvJobSearch.addItemDecoration(new RecyclerDivider(
                mContext, LinearLayoutManager.VERTICAL, DensityUtil.dp2px(getContext(), 8), ContextCompat.getColor(getContext(), R.color.gray_background)));
        rcvJobSearch.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                search();
            }
        });
    }

    private void search() {
        if (TextUtils.isEmpty(key)) {
            return;
        }
        User user = DataCacheManager.getInstance().getUser();
        if (user == null) {
            return;
        }
        showLoading();
        enqueue(createCallService(HeadHunterService.class).getCompanyJobList(key, user.getEnterpriseId(), curPage, AppConfig.PagSize), new RetrofitCallbackListener<JobListResp>() {
            @Override
            public void onSuccess(Call<JobListResp> call, JobListResp result) {
                rcvJobSearch.loadMoreComplete();
                misLoading();
                if (result.getData() != null && result.getData().getResultList() != null) {
                    if (curPage == 1) {
                        dataList.clear();
                    }
                    if (result.getData().getPageInfo() == null) {
                        rcvJobSearch.setCanLoadMore(false);
                    } else {
                        rcvJobSearch.setCanLoadMore(result.getData().getPageInfo().isHasMore());
                    }
                    dataList.addAll(result.getData().getResultList());
                    curPage++;
                    rcvJobSearch.notifyData();
                }
                if (!CollectionUtils.hasData(dataList)) {
                    emptyView.loadCompleteNoData(R.mipmap.holder_no_job,R.string.search_none);
                } else {
                    emptyView.loadComplete();
                }
            }

            @Override
            public void onError(String msg) {
                rcvJobSearch.loadMoreComplete();
                misLoading();
                if (!CollectionUtils.hasData(dataList)) {
                    emptyView.loadCompleteNoData(R.mipmap.holder_no_job,R.string.search_none);
                } else {
                    emptyView.loadComplete();
                }
            }
        });
    }

    //删除职位
    private void deleteJob(final String positionId, final int position) {
        new PromptBuilderDialog(getContext())
                .setContent("确定删除该条职位信息？")
                .setNegative(R.string.cancel)
                .setPositive(R.string.confirm)
                .setActionClickListener(new DialogActionListener() {
                    @Override
                    public void confirm(DialogInterface dialog, int which) {
                        enqueue(createCallService(HeadHunterService.class).deleteCompanyJob(positionId), new RetrofitCallbackListener<BaseEntity>() {
                            @Override
                            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                                dataList.remove(position);
                                rcvJobSearch.notifyData();
                                if (!CollectionUtils.hasData(dataList)) {
                                    emptyView.loadCompleteNoData(R.mipmap.holder_no_job,R.string.search_none);
                                }
                                isEdited = true;
                            }

                            @Override
                            public void onError(String msg) {

                            }
                        });
                    }

                    @Override
                    public void cancel(DialogInterface dialog, int which) {

                    }
                }).show();
    }

    //上下架职位
    private void showJobToUser(final JobBean job, final int type) {
        String tip = type == 0 ? "是否确定下架该条职位？" : "是否确定上架该条职位";
        new PromptBuilderDialog(getContext())
                .setContent(tip)
                .setPositive(R.string.confirm)
                .setNegative(R.string.cancel)
                .setActionClickListener(new DialogActionListener() {
                    @Override
                    public void confirm(DialogInterface dialog, int which) {
                        enqueue(createCallService(HeadHunterService.class).updateJob(job.getId(), type), new RetrofitCallbackListener<BaseEntity>() {
                            @Override
                            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                                job.setStatus(type);
                                rcvJobSearch.notifyData();
                                isEdited = true;
                            }

                            @Override
                            public void onError(String msg) {

                            }
                        });
                    }

                    @Override
                    public void cancel(DialogInterface dialog, int which) {

                    }
                }).show();
    }

    @Override
    public void onBackPressed() {
        if (isEdited) {
            setResult(1992);
        }
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1991 && resultCode == 1992) {
            isEdited = true;
            curPage = 1;
            search();
        }
    }

    @OnClick(R.id.tv_cancel_search)
    public void onViewClicked() {
        onBackPressed();
    }
}
